import Vue from 'vue';
import Axios from 'axios';
import Qs from 'qs';
import Datepicker from 'vuejs-datepicker';
import {zh} from 'vuejs-datepicker/dist/locale';
import VModal from 'vue-js-modal';
import Map from '../components/map/map.js';
import '../basic/basic.css';
import '../activity/edit-default.css';
import LoadingImg from './images/loading.gif';
import HelpImg from './images/help.png';
import E from 'wangeditor';

Vue.use(VModal,{dialog:true});

new Vue({
    el:'#louie-edit',
    data:{
        activity_id:0,  //活动id
        doing:'add', //add  活动创建 edit活动编辑
        status:1,   //活动状态0=创建中，1=未开始，2=进行中，3=结束
        loading_img:LoadingImg,  //创建宝箱坐标加载动画
        help_img:HelpImg,  //查看帮助图标
        //--公共--
        url:$('#louie-edit').attr('data-url'),
        attachment:sysinfo.attachurl_local,
        //步骤导航
        step_selected:1,
        step:[
            {
                text:'选择活动区域',
                value:1,
                pass:false,
            },
            {
                text:'基本信息',
                value:2,
                pass:false
            },
            {
                text:'活动配置',
                value:3,
                pass:false
            },
            {
                text:'投放虚拟宝藏',
                value:4,
                pass:false
            },
            {
                text:'投放实体宝藏',
                value:5,
                pass:false
            },
            {
                text:'活动说明',
                value:6,
                pass:false
            }
        ],
        //step1数据
        address:'',  //活动地址
        m_coords:[],  //地图组件选中的区域
        map_coords:[],  //选择的活动区域数据
        min_area:1000,   //选取区域最小平方米
        loading:{  //是否正在创建加载
            status:false,
            text:'正在创建宝箱投放坐标，请耐心稍等...'
        },
        //step2基本信息
            //Datepicke
        date:{
            zh:zh
        },
            //--时间--
        times:[],   //24小时时间选择器
        start_date:new Date(),  //活动开始日期
        end_date:new Date(),   //活动结束日期
        start_time:'12:00',  //开始时间
        end_time:'12:00',  //结束时间
            //--数据--
        name:'',  //名称
        response_keyword:'',  //关键词
        open3d:0,  //是否开启3d地图
        cover:'',   //活动封面
        brief:'',  //活动简介
        //--step3活动配置--
        init_bz_number:0,  //用户初始可开宝箱
        open_distance:5, //用户开宝箱的距离
        bz_number:0,  //活动地图宝箱显示数量
        //--step4虚拟宝藏
        ud_id:0,  //要修改和删除宝藏的id
        bz_doing:'add',
        bz_update:0, //是否修改了虚拟宝藏
        bz_list:[],   //系统宝藏列表
        activity_bz:[],   //活动宝藏列表
        bz_index:0,  //选中宝藏的下标
        money:null,   //宝藏的定价
        number:1,  //投放宝藏的数量
        user_number:0,  //用户可开宝藏数量
        win_odds:10,   //宝藏中奖率
        bz_win_odds:5,  //虚拟宝藏的中奖率
        //--step5实体宝藏--
        entity_doing:'add',  //实物操作
        update_entity:0,  //是否修改了实物列表
        entity_index:0,  //操作的实物列表下标
        entity_address:'',  //实体奖励兑换地址
        entity_list:[],  //实体宝藏列表
        entity_win_odds:5,  //实物宝藏的中奖率
        entity_name:'',  //实物名称
        //--step6活动说明--
        explain:'',
        explain_status:1,  //活动说明的审核状态
        //--step7转发分享设置--
        open_share:0,   //是否开启转发分享
        add_bz:1   //成功邀请新增可开宝箱数量
    },
    components:{
        'date-picker':Datepicker,
        'louie-map':Map
    },
    created:function(){
        this.checkActivity();
        this.createTimes();
        if(this.doing == 'edit'){
            this.find();
        }
    },
    mounted:function(){
        this.initWangEditor();
    },
    watch:{
        bz_win_odds:function(){
            this.entity_win_odds = 10 - this.bz_win_odds;
        },
        entity_win_odds:function(){
            this.bz_win_odds = 10 - this.entity_win_odds;
        }
    },
    //计算属性
    computed:{
        //活动开始时间
        start:function(){
            return this.startEnd(this.start_date,this.start_time);
        },
        //活动结束时间
        end:function(){
            return this.startEnd(this.end_date,this.end_time);
        },
        //活动投入资金
        invest:function(){
            if(this.activity_bz.length > 0){
                var sum = 0;
                for(var i=0;i<this.activity_bz.length;i++){
                    sum += parseFloat(this.activity_bz[i].money) * this.activity_bz[i].number;
                }
                return this.toDecimal2(sum);
            }else{
                return '0.00';
            }
        }
    },
    methods:{
        //点击步骤
        clickStep:function(value){
            if(value != this.step_selected){
                if(!this.checkStep(value)) return;
                this.step_selected = value;
            }
        },
        //上一步
        stepPrev:function(){
            if(this.step_selected <= 1) return;
            if(!this.checkStep(this.step_selected - 1)) return;
            this.step_selected --;
        },
        //下一步
        stepNext:function(){
            if(this.step_selected >= this.step.length) return;
            if(!this.checkStep(this.step_selected + 1)) return;
            this.step_selected ++;
        },
        //地图返回选中地图区域坐标
        returnCoords:function(event){
            this.map_coords = event;
            this.alert('成功设置活动区域');
        },
        //计算开始结束时间戳
        startEnd:function(date,time){
            var year = date.getFullYear();
            var month = date.getMonth()+1;
            var day = date.getDate();
            return new Date(year+'/'+month+'/'+day+' '+time).getTime()/1000;
        },
        //生成时间
        createTimes:function(){
            for(var i=0;i<=23;i++){
                var h = i;
                if(h < 10){
                    h='0'+h;
                }
                for(var j=0;j<60;j++){
                    var m = j;
                    if(m<10){
                        m='0'+m;
                    }
                    this.times.push(h+':'+m);
                }
            }
        },
        //显示隐藏宝藏列表区域
        toggleBzList:function(){
            $('#add-bz-box').modal('toggle');
            this.bz_doing = 'add';
            if(this.bz_list.length <=0){
                this.getBzList();
            }
        },
        //初始化wang富文本编辑器
        initWangEditor:function(){
            var self = this;
            this.editor = new E(this.$refs.editor);
            this.editor.customConfig.uploadImgServer = this.url;
            this.editor.customConfig.zIndex = 10;
            this.editor.customConfig.uploadImgParams = {
                pages:'editor',
                doing:'uploadEditorImage'
            }
            this.editor.customConfig.onchange = function(html){
                self.explain = html;
            }
            this.editor.create();
        },
        //获取系统宝藏列表
        getBzList:function(){
            Axios.post(this.url,Qs.stringify({
                pages:'treasure',
                doing:'li'
            }))
                .then((res)=>{
                    if(res.data.status == 'success'){
                        if(this.doing == 'edit'){
                            var data = res.data.data;
                            for(var i=0;i<data.length;i++){
                                var is_push = true;
                                for(var j=0;j<this.activity_bz.length;j++){
                                    if(data[i].name == this.activity_bz[j].name){
                                        is_push = false;
                                        break;
                                    }
                                }
                                if(is_push) this.bz_list.push(data[i]);
                            }
                        }else{
                            this.bz_list = res.data.data;
                        }
                    }
                })
                .catch(error=>console.log(error));
        },
        //新增修改活动宝藏
        addBz:function(){
            if(this.money == 0 || !/(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/.test(this.money)){
                this.alert('请输入正确的宝藏价值');
                return;
            }
            if(!/^\d+$/.test(this.number) || this.number <= 0){
                this.alert('请输入正确的投放数量');
                return;
            }
            if(this.user_number != parseInt(this.user_number)){
                this.alert('请输入正确的用户获得数量');
                return false;
            }
            if(this.win_odds != parseInt(this.win_odds) || this.win_odds < 1){
                this.alert('请输入正确的中奖率');
                return false;
            }
            $('#pricing').modal('toggle');
            this.bz_update = 1;
            var tempObj = {};
            tempObj.name = this.bz_list[this.bz_index].name;
            tempObj.icon = this.bz_list[this.bz_index].icon;
            tempObj.icon_url = this.bz_list[this.bz_index].icon_url;
            tempObj.money = this.money;
            tempObj.number = this.number;
            tempObj.user_number = this.user_number;
            tempObj.win_odds = this.win_odds;
            this.activity_bz.push(tempObj);
            this.bz_list.splice(this.bz_index,1);
        },
        //修改宝藏
        editBz:function(){
            if(this.money == 0 || !/(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/.test(this.money)){
                this.alert('请输入正确的宝藏价值');
                return;
            }
            if(!/^\d+$/.test(this.number) || this.number <= 0){
                this.alert('请输入正确的投放数量');
                return;
            }
            if(this.user_number != parseInt(this.user_number)){
                this.alert('请输入正确的用户获得数量');
                return false;
            }
            if(this.win_odds != parseInt(this.win_odds) || this.win_odds < 1){
                this.alert('请输入正确的中奖率');
                return false;
            }
            $('#pricing').modal('toggle');
            this.bz_update = 1;
            this.activity_bz[this.bz_index].money = this.money;
            this.activity_bz[this.bz_index].number = this.number;
            this.activity_bz[this.bz_index].win_odds = this.win_odds;
            this.activity_bz[this.bz_index].user_number = this.user_number;
        },
        //显示隐藏宝藏定价区域
        togglePricing:function(){
            $('#pricing').modal('toggle');
        },
        //移除活动宝藏
        removeActivityBz:function(){
            this.bz_update = 1;
            this.bz_list.push(this.activity_bz[this.bz_index]);
            this.activity_bz.splice(this.bz_index,1);
        },
        //点击虚拟宝藏
        clickBz:function(index){
            var self = this;
            this.bz_index = index;
            this.$modal.show('dialog',{
                text:'操作虚拟宝藏',
                buttons:[
                    {
                        title: '修改',
                        handler:function(){
                            self.$modal.hide('dialog');
                            self.bz_doing = 'edit';
                            var bz = self.activity_bz[index];
                            bz.id && (self.ud_id = bz.id);
                            self.money = bz.money;
                            self.number = bz.number;
                            self.user_number = bz.user_number;
                            self.win_odds = bz.win_odds;
                            self.togglePricing(index);
                        }
                    },
                    {
                        title: '删除',
                        default: true,
                        handler:function(){
                            self.$modal.hide('dialog');
                            self.removeActivityBz();
                        }
                    },
                    {
                        title: '关闭',
                        default: true,
                        handler:function(){
                            self.$modal.hide('dialog');
                        }
                    }
                ]
            });
        },
        //点击系统的宝藏列表
        clickSystem:function(index){
            this.bz_doing = 'add';
            this.money = null;
            this.number = 1;
            this.user_number = 0;
            this.win_odds = 10;
            this.bz_index = index;
            this.togglePricing();
        },
        //验证step数据
        checkStep:function(step){
            for(let i=1;i<step;i++){
                if(i == 1){
                    if(this.address == ''){
                        this.alert('请设置活动地址');
                        return false;
                    }
                    if(this.map_coords.length <= 0){
                        this.alert('请先选择活动区域');
                        return false;
                    }
                }
                if(i == 2){
                    if(this.name == ''){
                        this.alert('活动名称不能为空');
                        return false;
                    }
                    if(this.name.length > 20){
                        this.alert('活动名称长度不能大于20位');
                        return false;
                    }
                    if(this.response_keyword == ''){
                        this.alert('活动响应关键词不能为空');
                        return false;
                    }
                    if(this.response_keyword.length > 6){
                        this.alert('活动响应关键词不能大于6位');
                        return false;
                    }
                    if(document.querySelector('.activity-cover input').value == ''){
                        this.alert('请设置活动封面');
                        return false;
                    }
                    var nowTime = new Date().getTime()/1000;
                    if(nowTime >= this.start && this.doing == 'add'){
                        this.alert('活动开始时间不能小于当前时间');
                        return false;
                    }
                    if(this.start >= this.end){
                        this.alert('活动结束时间必须大于开始时间');
                        return false;
                    }
                    if(this.brief.length > 255){
                        this.alert('活动简介长度不能大于255');
                        return false;
                    }
                }
                if(i == 3){
                    if(parseInt(this.init_bz_number) != this.init_bz_number){
                        this.alert('请输入正确的会员可开宝箱数量');
                        return false;
                    }
                    if(parseInt(this.open_distance) != this.open_distance){
                        this.alert('请输入正确的宝箱打开距离');
                        return false;
                    }
                    if(this.open_distance < 1){
                        this.alert('宝箱打开距离不能小于1米');
                        return false;
                    }
                    if(parseInt(this.bz_number) != this.bz_number){
                        this.alert('请输入正确的宝箱显示数量');
                        return false;
                    }
                }
                if(i == 4){
                    if(this.bz_win_odds == NaN || (parseInt(this.bz_win_odds) != this.bz_win_odds)){
                        this.alert('请输入正确的宝藏中奖率');
                        return false;
                    }
                    if(this.bz_win_odds < 0 || this.bz_win_odds > 10){
                        this.alert('宝藏中奖率取值范围0-10');
                        return false;
                    }
                }
                if(i == 5){
                    if(this.entity_list.length > 0 && this.entity_address == ''){
                        this.alert('请设置实物奖励的领取地址');
                        return false;
                    }
                }
            }
            return true;
        },
        //补充两个小数点
        toDecimal2:function(x){
            var f = parseFloat(x);
            if (isNaN(f)) {
                return false;
            }
            var f = Math.round(x*100)/100;
            var s = f.toString();
            var rs = s.indexOf('.');
            if (rs < 0) {
                rs = s.length;
                s += '.';
            }
            while (s.length <= rs + 2) {
                s += '0';
            }
            return s;
        },
        //alert
        alert:function(text,call){
            var self = this;
            this.$modal.show('dialog',{
                text:text,
                buttons:[
                    {
                        title:'关闭',
                        handler:function(){
                            self.$modal.hide('dialog');
                            typeof call =='function' && call();
                        }
                    },
                ]
            });
        },
        //confirm
        confirm:function(text,call){
            var self = this;
            this.$modal.show('dialog',{
                text:text,
                buttons:[
                    {
                        title: '取消',
                        handler:function(){
                            self.$modal.hide('dialog');
                            call(false);
                        }
                    },
                    {
                        title: '确认',
                        default: true,
                        handler:function(){
                            self.$modal.hide('dialog');
                            call(true);
                        }
                    }
                ]
            });
        },
        //点击创建活动
        clickSubmit:function(){
            if(!this.checkStep(10)) return;
            if(!this.submitCheck()) return;
            var data = {
                name:this.name,
                response_keyword:this.response_keyword,
                open3d:this.open3d,
                cover:document.querySelector('.activity-cover input').value,
                invest:this.invest,
                init_bz_number:this.init_bz_number,
                open_distance:this.open_distance,
                bz_number:this.bz_number,
                brief:this.brief,
                address:this.address,
                start:this.start,
                end:this.end,
                map_coords:JSON.stringify(this.map_coords),
                explain:this.explain,
                entity_address:this.entity_address,
                bz_win_odds:this.bz_win_odds,
                entity_win_odds:this.entity_win_odds,
            };
            if(this.doing == 'add'){
                this.startLoading('活动创建中...');
                data.activity_bz = this.activity_bz;
                data.entity_list = this.entity_list;
                data.open_share = this.open_share;
                data.add_bz = this.add_bz;
                this.add(data);
            }else{
                this.startLoading('活动修改中...');
                data.open_share = this.open_share;
                data.add_bz = this.add_bz;
                this.edit(data);
            }
        },
        //新增活动
        add:function(data){
            var self = this;
            Axios.post(this.url,Qs.stringify({
                pages:'activity',
                doing:'add',
                data:data
            }))
                .then(res=>{
                    if(res.data.status == 'success'){
                        this.activity_id = res.data.data;
                        this.doing = 'edit';
                        self.endLoading();
                        self.alert('创建成功',function(){
                            window.location.href = sysinfo.siteurl+'#doing=edit#activity_id='+self.activity_id;
                        });
                    }else{
                        this.endLoading();
                        this.alert(res.data.err_msg);
                    }
                })
                .catch(error=>console.log(error));
        },
        //修改活动
        edit:function(data){
            var self = this;
            var requireArr = [this.editMain(data)];
            if(this.update_entity == 1){
                requireArr.push(this.editEntityList());
            }
            if(this.bz_update == 1){
                requireArr.push(this.editBzList());
            }
            Axios.all(requireArr)
                .then(Axios.spread(function(main){
                    if(main.data.status == 'success'){
                        self.update_entity = 0;
                        self.bz_update = 0;
                        self.explain_status = 1;
                        self.alert('修改成功');
                    }
                    self.endLoading();
                }))
                .catch(error=>console.log(error));
        },
        //修改主体活动
        editMain:function(data){
            return Axios.post(this.url,Qs.stringify({
                pages:'activity',
                doing:'edit',
                data:data,
                activity_id:this.activity_id
            }));
        },
        //修改活动的实体宝藏列表
        editEntityList:function(){
            return Axios.post(this.url,Qs.stringify({
                pages:'activity',
                doing:'editEntity',
                activity_id:this.activity_id,
                entity_list:this.entity_list
            }));
        },
        //修改活动的虚拟宝藏列表
        editBzList:function(){
            return Axios.post(this.url,Qs.stringify({
                pages:'activity',
                doing:'editBz',
                activity_id:this.activity_id,
                activity_bz:this.activity_bz
            }));
        },
        //提交数据验证
        submitCheck:function(){
            if(this.activity_bz.length <= 0 && this.entity_list.length <= 0){
                this.alert('请设置投放宝藏');
                return false;
            }
            return true;
        },
        //点击添加活动的实物
        clickAddEntity:function(){
            this.entity_doing = 'add';
            this.entity_name='';
            document.edit_entity.entity_icon.value ='';
            $('.entity-icon-img .img-thumbnail')[0].src = './resource/images/nopic.jpg';
            this.money='';
            this.entity_number=1;
            this.win_odds=10;
            this.user_number = 1;
            this.toggleEntity();
        },
        //显示隐藏添加修改实物区域
        toggleEntity:function(){
            $('#add-entity-box').modal('toggle');
        },
        //确认添加活动实物
        submitEntity:function(){
            if(!this.checkEntity()) return;
            var data = {
                name:this.entity_name,
                icon:document.edit_entity.entity_icon.value,
                icon_url:$('.entity-icon-img .img-thumbnail')[0].src,
                money:this.money,
                number:this.number,
                user_number:this.user_number,
                win_odds:this.win_odds
            };
            if(this.entity_doing == 'add'){
                this.addEntity(data);
            }else{
                data.id = this.ud_id;
                this.editEntity(data);
            }
        },
        //添加实物奖励
        addEntity:function(data){
            data.type = 2;
            this.entity_list.push(data);
            this.update_entity = 1;
            this.toggleEntity();
        },
        //修改编辑实物奖励
        editEntity:function(data){
            for(var attr in data){
                this.entity_list[this.entity_index][attr] = data[attr];
            }
            this.update_entity = 1;
            this.toggleEntity();
        },
        //删除活动投放的实物
        delEntity:function(){
            this.update_entity = 1;
            this.entity_list.splice(this.entity_index,1);
        },
        //验证添加活动实物
        checkEntity:function(){
            if(this.entity_name == ''){
                this.alert('名称不能为空');
                return false;
            }
            if(this.entity_name.length > 20){
                this.alert('名称长度不能大于20');
                return false;
            }
            if(this.money <= 0 || !/(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/.test(this.money)){
                this.alert('请输入正确的实物价值');
                return false;
            }
            if(this.number != parseInt(this.number) || this.number <= 0){
                this.alert('请输入正确的投放数量');
                return false;
            }
            if(this.user_number != parseInt(this.user_number)){
                this.alert('请输入正确的用户获得数量');
                return false;
            }
            if(this.win_odds != parseInt(this.win_odds) || this.win_odds < 1){
                this.alert('请输入正确的中奖率');
                return false;
            }
            if(document.edit_entity.entity_icon.value == ''){
                this.alert('请上传实物图片');
                return false;
            }
            return true;
        },
        //点击实物
        clickEntity:function(entity_index){
            var self = this;
            this.entity_doing = 'edit';
            this.entity_index = entity_index;
            this.$modal.show('dialog',{
                text:'操作实物宝藏',
                buttons:[
                    {
                        title: '修改',
                        handler:function(){
                            self.$modal.hide('dialog');
                            var entity = self.entity_list[entity_index];
                            self.entity_name = entity.name;
                            document.edit_entity.entity_icon.value = entity.icon;
                            $('.entity-icon-img .img-thumbnail')[0].src = entity.icon_url;
                            entity.id && (self.ud_id = entity.id);
                            self.money = entity.money;
                            self.number = entity.number;
                            self.user_number = entity.user_number;
                            self.win_odds = entity.win_odds;
                            self.toggleEntity();
                        }
                    },
                    {
                        title: '删除',
                        default: true,
                        handler:function(){
                            self.$modal.hide('dialog');
                            self.delEntity();
                        }
                    },
                    {
                        title: '关闭',
                        default: true,
                        handler:function(){
                            self.$modal.hide('dialog');
                        }
                    }
                ]
            });
        },
        //开始加载
        startLoading:function(text){
            this.loading.status = true;
            this.loading.text = text;
        },
        //结束加载
        endLoading:function(){
            this.loading.status = false;
        },
        //编辑验证活动
        checkActivity:function(){
            var hash = this.hash();
            if(hash.doing == 'edit'){
                this.doing = 'edit';
                if(hash.activity_id == undefined){
                    window.location.href = $('#louie-edit').attr('data-prev-page');
                    return false;
                }
                this.activity_id = hash.activity_id;
            }
        },
        //解析链接hash
        hash:function(){
            var hash = window.location.hash;
            hash = hash.substring(1);
            if(hash == '') return {};
            var tempArr = hash.split('#');
            var data = {};
            for(var i=0;i<tempArr.length;i++){
                var tArr = tempArr[i].split('=');
                data[tArr[0]] = tArr[1];
            }
            return data;
        },
        //获取数据
        find:function(){
            var self = this;
            Axios.post(this.url,Qs.stringify({
                pages:'activity',
                doing:'find',
                activity_id:this.activity_id
            }))
                .then((res)=>{
                    if(res.data.status == 'error'){
                        this.alert('活动不存在',function(){
                            window.location.href = $('#louie-edit').attr('data-prev-page');
                            return false;
                        });
                    }
                    var data = res.data.data;
                    this.start_date = new Date(data.start_date);
                    this.start_time = data.start_time;
                    this.end_date = new Date(data.end_date);
                    this.end_time = data.end_time;
                    this.map_coords = data.map_coords;
                    this.m_coords = data.map_coords;
                    this.name = data.name;
                    this.response_keyword = data.response_keyword;
                    this.open3d = data.open3d;
                    this.init_bz_number = data.init_bz_number;
                    this.open_distance = data.open_distance;
                    this.bz_number = data.bz_number;
                    this.brief = data.brief;
                    this.address = data.address;
                    this.entity_address = data.entity_address;
                    this.activity_bz = data.activity_bz;
                    this.entity_list = data.entity_list;
                    this.bz_win_odds = data.bz_win_odds;
                    this.entity_win_odds = data.entity_win_odds;
                    this.status = data.status;
                    this.open_share = data.open_share;
                    this.add_bz = data.add_bz;
                    this.explain = data.explain.explain;
                    this.explain_status = data.explain.status;
                    this.$nextTick(function(){
                        $('.activity-cover input').val(data.cover);
                        document.querySelector('.activity-cover .img-thumbnail').src = data.cover_url;
                        self.editor.txt.html(data.explain.explain);
                    })
                })
                .catch(error=>console.log(error));
        },
    }
});